package com.easy.base.api.controller;

import com.easy.base.api.model.dto.ResultBody;
import com.easy.base.api.model.dto.ResultPager;
import com.easy.base.api.model.entity.BaseEntity;
import com.easy.base.api.service.IService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

public class BaseController<E extends BaseEntity, S extends IService<E>> {
    @Autowired
    @SuppressWarnings("all")
    public S service;

    /** 新增实体 */
    public ResponseEntity<ResultBody<E>> insertEntity(E entity) {
        return ResponseEntity.ok().body(ResultBody.Success(true, service.insertEntity(entity)));
    }

    /** 更新实体 */
    public ResponseEntity<ResultBody<E>> updateEntity(String id, E entity) {
        entity.setId(id);
        return ResponseEntity.ok().body(ResultBody.Success(true, service.updateEntity(entity)));
    }

    /** 删除实体 */
    public ResponseEntity<ResultBody<String>> removeEntity(String id) {
        service.removeEntity(id);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).body(ResultBody.Success(true));
    }

    /** 删除多个实体 */
    public ResponseEntity<ResultBody<String>> removeEntity(String[] ids) {
        service.removeEntity(ids);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).body(ResultBody.Success(true));
    }

    /** 分页查询实体 */
    public ResponseEntity<ResultBody<ResultPager<E>>> selectEntities(E entity) {
        Page<E> pages = service.selectEntities(entity);
        return ResponseEntity.ok().body(
                ResultBody.Success(true, new ResultPager<E>(pages.toList(), pages.getNumber(), pages.getSize(),
                        pages.getNumberOfElements())));
    }

    /** 查询指定的实体 */
    public ResponseEntity<ResultBody<E>> selectEntity(String id) {
        return ResponseEntity.ok(ResultBody.Success(true, service.selectEntityByID(id)));
    }
}
